package org.rainbow.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LoginController {

	@GetMapping("/")
	public String index(){
		
		return "index";
	}
	
	@GetMapping("/login")
	public String login(){
		
		return "login";
	}
	
	@GetMapping("/unauth")
	public String unauth(){
		
		return "unauth";
	}
	
	@PostMapping("/login")
	public String doLogin(String username,String password,boolean rememberMe,Model model){
		
		System.out.println("rememberMe=========>" + rememberMe);
		
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username,password,rememberMe);
		String emsg="";
		
		try {
			subject.login(token);
		} catch (UnknownAccountException e) {
			emsg="用户名不存在";
		}catch (IncorrectCredentialsException e) {
			emsg="密码错误";
		}catch (LockedAccountException e) {
			emsg="账号被锁定";
		}catch (AuthenticationException e) {
			emsg="错误："+e.getMessage();
		}
		
		if(!StringUtils.hasText(emsg)){
			return "redirect:/";
		}
		
		model.addAttribute("emsg", emsg);
		
		return "login";
	}
	
}
